package com.rpp.study.service.impl;

import com.rpp.study.config.UserConfig;
import com.rpp.study.dao.LagouAuthCodeRepository;
import com.rpp.study.entity.LagouAuthCode;
import com.rpp.study.service.ICodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @Description
 * @Author rpp
 * @Date 2020/8/28 11:38 下午
 */
@Service
public class CodeService implements ICodeService {

    @Autowired
    LagouAuthCodeRepository lagouAuthCodeRepository;

    /**
     * 保存邮箱及对应验证码
     *
     * @param email
     * @param code
     */
    @Override
    public void save(String email, String code) {
        LagouAuthCode authCode = new LagouAuthCode();
        authCode.setEmail(email);
        authCode.setCode(code);

        Date now = new Date();
        authCode.setCreateTime(now);
        //验证码十分钟有效
        authCode.setExpireTime(new Date(now.getTime() + UserConfig.CODE_EXPIRE_TIME));

        lagouAuthCodeRepository.save(authCode);
    }

    /**
     * 校验验证码是否正确，0正确1错误2超时
     *
     * @param email
     * @param code
     * @return
     */
    @Override
    public Integer validate(String email, String code) {

        LagouAuthCode authCode = lagouAuthCodeRepository.findLatestOne(email, code);
        if (null == authCode) {
            return 1;
        }
        if (authCode.getExpireTime().before(new Date())) {
            return 2;
        }
        return 0;
    }
}
